﻿using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Xml;

using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.language;

namespace CreativeMinds.Umbraco.Dictionary2JS {
	public class JavascriptLanguageHandler : IHttpHandler {

		public bool IsReusable {
			get {
				return true;
			}
		}

		public void ProcessRequest(HttpContext context) {
			context.Response.Charset = "utf-8";
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.ContentType = "text/html";

			string url = context.Request.Url.PathAndQuery;
			string cachedValue = (string)context.Cache.Get(url);

			string culture = context.Request.QueryString["culture"];
			string snippet = context.Request.QueryString["xslt"];

			if (String.IsNullOrEmpty(cachedValue) && !String.IsNullOrEmpty(culture)) {
				Language[] languages = Language.getAll;
				int languageId = languages[0].id;
				try {
					CultureInfo ci = new CultureInfo(culture);
					Thread.CurrentThread.CurrentCulture = ci;
					Thread.CurrentThread.CurrentUICulture = ci;
					foreach (Language lan in languages) {
						if (lan.CultureAlias == ci.Name) {
							languageId = lan.id;
							break;
						}
					}
				}
				catch {
				}

				XmlDocument xml = new XmlDocument();
				xml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?><Items />");
				XmlNode root = xml.SelectSingleNode("Items");

				Dictionary.DictionaryItem[] items = Dictionary.getTopMostItems;
				foreach (Dictionary.DictionaryItem item in items) {
					XmlNode itemNode = item.ToXml(xml);
					root.AppendChild(itemNode);
				}

				cachedValue = SnippetRenderer.Render(xml, snippet, languageId, culture);

				// TODO:
				//context.Cache.Add(url, cachedValue, null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
				context.Cache.Add(url, cachedValue, new CacheDependency(HttpContext.Current.Server.MapPath("/xslt/" + snippet)), DateTime.Now.AddDays(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
			}

			context.Response.Write(cachedValue);
		}
	}
}